package cn.dyw.shop.service;

import cn.dyw.shop.dao.OrderDao;
import cn.dyw.shop.model.Goods;
import cn.dyw.shop.model.Order;
import cn.dyw.shop.model.OrderItem;
import cn.dyw.shop.service.imp.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author: dyw770
 * @date: 2018/5/5
 */
@Service
public class OrderService extends BaseService<Order> {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    public void setAddressDao(OrderDao OrderDao) {
        this.repository = orderDao;
    }

    public List<Order> findAllByUserId(Integer id) {
        return orderDao.findAllByUserId(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void pay(Order one) {
        one.setPay(true);
        save(one);
        List<OrderItem> orderItems = one.getOrderItems();
        List<Goods> goodsList = new ArrayList<>();
        for (OrderItem item : orderItems) {
            item.getGoods().setSalesVolume(item.getGoods().getSalesVolume() + item.getNum());
            item.getGoods().setStock(item.getGoods().getStock() - item.getNum());
            goodsList.add(item.getGoods());
        }
        goodsService.save(goodsList);
    }
}
